// no-console-plugin.js 方式2：完整代码
const generator = require('@babel/generator');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse');
const types = require('@babel/types');

// 是否包含需要处理的文件类型
String.prototype.includesFileType = function(suffixs){
  const arr = this.toString().split('.');
  return suffixs.includes(arr[arr.length - 1]);
};

function isJs(filename){
  const arr = filename.split('.');
  return ['js'].includes(arr[arr.length - 1]);
};

class NoConsolePlugin {
  apply(compiler) {
    // emit钩子函数：输出 asset 到 output 目录之前执行
    compiler.hooks.emit.tap('NoConsolePlugin',(compilation) => {
      for (const name in compilation.assets) {
        // 只需要处理js文件
        if(isJs(name)){
          const content = compilation.assets[name].source();
          let ast = parser.parse(content);
          traverse.default(ast, {
            // 遍历调用表达式
            CallExpression(path) {
              const { callee } = path.node;
              if (types.isCallExpression(path.node) && types.isMemberExpression(callee)) {
                const { object, property } = callee;
                if (object.name === 'console' && property.name === 'log') {
                  path.remove();
                }
              }
            },
          });
          const transformCode = generator.default(ast, {
            minified: true
          }).code;
          compilation.assets[name] = {
            source: () => transformCode,
            size: () => transformCode.length
          }
        }
      }
    });
  }
};

module.exports = NoConsolePlugin;
